package com.lzb.auth.web.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.lzb.auth.common.constant.ConstantValues;
import com.lzb.auth.domain.MngUser;

public class LoginInterceptor implements HandlerInterceptor {

	public LoginInterceptor() {}
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//请求路径
		String url = request.getRequestURI();
		int position = StringUtils.lastIndexOf(url, "/");
		String path = url.substring(position + 1);
		MngUser user =  (MngUser)request.getSession().getAttribute(ConstantValues.USER_LOGIN);
		if(StringUtils.startsWithIgnoreCase(path, "doNotNeedSecurity")) {
			return true;
		} else {
			if(user == null) {
				//拦截异步请求
				if (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With").equalsIgnoreCase(     
						"XMLHttpRequest")) {  
						response.setCharacterEncoding("text/html;charset=utf-8");
						response.setContentType("text/html;charset=utf-8");
						PrintWriter pw = response.getWriter();
						pw.write("sessionTimeOut");
						pw.flush();
						pw.close();
						return false;
				}
				response.sendRedirect(request.getContextPath()+"/resources/global/jsp/noSession.jsp");  
				return false;
			} 
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
